package com.kinon.norogamilk.ui.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.google.gson.Gson;
import com.kinon.norogamilk.R;
import com.kinon.norogamilk.adapter.AdViewPagerAdapter;
import com.kinon.norogamilk.bean.AdBean;
import com.kinon.norogamilk.bean.ComBean;
import com.kinon.norogamilk.http.MilkApi;
import com.kinon.norogamilk.http.StrCallback;
import com.kinon.norogamilk.ui.base.BaseActivity;
import com.kinon.norogamilk.util.RxBus;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Response;


public class MainActivity extends BaseActivity implements
        View.OnClickListener {
    ArrayList<AdBean> adList = new ArrayList<>();
    ViewGroup group;
    private Button btn_selfBuy;
    private Button btn_menberPickup;
    private Button btn_pwdPickup;
    private TextView tv_temperature;
    private FrameLayout fl_ad;
    private ViewPager vp_ad;
    private LinearLayout ll_ad;
    private VideoView video_home;
    private RelativeLayout rl_home;
    private ArrayList<View> viewList = new ArrayList<>();
    private ImageView[] indicator_imgs;
    private MyThread myThread = new MyThread();

//    private SerialControl mSerCon;

    private int waitTime = 0;
    private MediaController controller;
    private ViewPager.OnPageChangeListener vpOnListenner = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            // 修改全部的position长度
            int newPosition = position % viewList.size();
            // 循环设置当前页的标记图
            int length = adList.size();
            for (int i = 0; i < length; i++) {
                if (i == newPosition) {
                    indicator_imgs[i]
                            .setBackgroundResource(R.drawable.img_onpoint);
                } else {
                    indicator_imgs[i]
                            .setBackgroundResource(R.drawable.img_point);
                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };
    private Handler adHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (vp_ad.getCurrentItem() == indicator_imgs.length - 1) {
                        vp_ad.setCurrentItem(0);
                    } else {
                        vp_ad.setCurrentItem(vp_ad.getCurrentItem() + 1);
                    }
                    if (waitTime >= 10) { //一分钟没人点击就进入广告
                        if (controller == null) {
                            videoViewSet();
                        } else {
                            video_home.setVisibility(View.VISIBLE);
                            rl_home.setVisibility(View.GONE);
                            video_home.start();
                        }
                        waitTime = 0;
                        myThread.setIsSleep(true);
                    }
                    break;

                default:
                    break;
            }
        }

    };
    private int msign = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);
        setContentView(R.layout.activity_main);
//        mSerCon=new SerialControl();
        OpenComPort(mSerCon);
        initView();
//        sendString();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
            case KeyEvent.KEYCODE_HOME:
            case KeyEvent.KEYCODE_MENU:
            case KeyEvent.KEYCODE_VOLUME_DOWN:
            case KeyEvent.KEYCODE_VOLUME_UP:
            case KeyEvent.KEYCODE_VOLUME_MUTE:
                mToast("按键被禁止了");

                return true;
            default:
                return false;
        }

//        return super.onKeyDown(keyCode, event);
//        return false;

    }

    private void initView() {
        btn_selfBuy = findViewById(R.id.btn_selfBuy);
        btn_menberPickup = findViewById(R.id.btn_menberPickup);
        btn_pwdPickup = findViewById(R.id.btn_pwdPickup);
        tv_temperature = findViewById(R.id.tv_temperature);
        fl_ad = findViewById(R.id.fl_ad);
        vp_ad = findViewById(R.id.vp_ad);
        group = findViewById(R.id.ll_ad);
        video_home = findViewById(R.id.video_home);
        rl_home = findViewById(R.id.rl_home);

        btn_selfBuy.setOnClickListener(this);
        btn_menberPickup.setOnClickListener(this);
        btn_pwdPickup.setOnClickListener(this);
        tv_temperature.setOnClickListener(this);
        video_home.setOnClickListener(this);
//        sendPortData("4546CB0300900000f796");
        getAd();
//        videoViewSet();

    }

    private void videoViewSet() {

        video_home.setVisibility(View.VISIBLE);
        rl_home.setVisibility(View.GONE);
        controller = new MediaController(this);
        video_home.setMediaController(controller);
//        video_home.setVideoPath();
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/noroga.mp4";
        File file = new File(path);
        if (!file.exists()) {
            Log.e("lh", "文件路径错误=== ");
        }

        video_home.setVideoPath(path);
//        Log.e("lh", "getCacheDir=== "+ getCacheDir()+"/mp.mp4");

        Log.e("lh", "path=== " + path);
//        controller.setMediaPlayer(video_home);
        video_home.start();
        video_home.requestFocus();
        video_home.seekTo(0);
        video_home.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                mediaPlayer.start();
                mediaPlayer.setLooping(true);
            }
        });
        video_home.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                video_home.pause();
                myThread.setIsSleep(false);
                video_home.setVisibility(View.GONE);
                rl_home.setVisibility(View.VISIBLE);
                waitTime = 0;
                return false;
            }
        });


    }

    private void getAd() {
//        Log.e("lh", "serialNum=="+MilkApp.serialNum);
//        Log.e("lh", "serialNum=="+MilkApp.androidId );
        Call<String> call = MilkApi.getInstance().getAd(sn);
        call.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response, String data) {
                Gson gson = new Gson();
                try {
                    JSONArray array = new JSONArray(data);
                    for (int i = 0; i < array.length(); i++) {
                        AdBean adbean = gson.fromJson(array.get(i).toString(), AdBean.class);
                        adList.add(adbean);
                    }
                    addViewList();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(int code, String error) {
                mToast(error);
            }
        });

    }

    //幻灯片设置
    private void addViewList() {
        if (adList.size() > 0) {
            myThread.start();
            myThread.setIsSleep(false);
        }
        LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
        /**
         * 创建多个item （每一条viewPager都是一个item）
         * 从服务器获取完数据（如文章标题、url地址） 后，再设置适配器
         */
        int adlenth = adList.size();
        viewList.clear();
        for (int i = 0; i < adlenth; i++) {
            View item = inflater.inflate(R.layout.item_viewpager_ad, null);
            viewList.add(item);
        }
        vp_ad.setAdapter(new AdViewPagerAdapter(MainActivity.this, viewList, adList));
        vp_ad.setOnPageChangeListener(vpOnListenner);
        initIndicator();
    }

    private void initIndicator() {
//        ImageView roundview;
        int adsize = adList.size();
        group.removeAllViews();
        indicator_imgs = new ImageView[adsize];
        LinearLayout.LayoutParams params_linear = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params_linear.setMargins(8, 10, 8, 10);
        for (int i = 0; i < adsize; i++) {
            ImageView roundview = new ImageView(MainActivity.this);
            roundview.setLayoutParams(params_linear);
            indicator_imgs[i] = roundview;
            if (i == 0) {
                indicator_imgs[i]
                        .setBackgroundResource(R.drawable.img_onpoint);
            } else {
                indicator_imgs[i]
                        .setBackgroundResource(R.drawable.img_point);
            }
            ((ViewGroup) group).addView(indicator_imgs[i]);
        }
    }

    @Override
    public void onClick(View view) {
        waitTime = 0;
        switch (view.getId()) {
            case R.id.btn_selfBuy:
                Intent intent = new Intent(MainActivity.this,
                        SelfBuyActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_menberPickup:
                Intent intentM = new Intent(MainActivity.this,
                        MemberTakeActivity.class);
                startActivity(intentM);
                break;
            case R.id.btn_pwdPickup:
                Intent intentP = new Intent(MainActivity.this,
                        PwdTakeActivity.class);
                startActivity(intentP);
                break;
            case R.id.tv_temperature:
                Intent intentR = new Intent(MainActivity.this,
                        NewRepairActivity.class);
                startActivity(intentR);
                break;
            case R.id.video_home:
//                video_home.pause();
//                myThread.setIsStop(false);
//                video_home.setVisibility(View.GONE);
//                rl_home.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDataReceiv(final ComBean ComRecData) {
        super.onDataReceiv(ComRecData);
        RxBus.getDefault().post(ComRecData);
//        Log.e(TAG, "Main =="+MyFunc.ByteArrToHex(ComRecData.getbRec()));

        if (ComRecData.getbRec().length > 6) {
            if (ComRecData.getbRec()[5] == -112) { //获取温度的命令
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (ComRecData.getbRec().length == 16) {
                            tv_temperature.setText("温度" + ComRecData.getbRec()[10] + "℃");
                        }
                    }
                });
            } else if (ComRecData.getbRec()[5] == -116) { //打开补货
                Intent intentR = new Intent(MainActivity.this,
                        NewRepairActivity.class);
                startActivity(intentR);
            }

        }

//        req(ComRecData);

    }

    private void req(ComBean comBean) {
        if (comBean.getbRec().length > 6) {

            Log.e(TAG, "getbRec ==" + comBean.getbRec()[5]);
            if (comBean.getbRec()[5] == -113) { //微波炉开关控制返回
                if (comBean.getbRec().length > 9) {
                    msign = 0;

                    if (comBean.getbRec()[8] == 1) { //电源开启
                        Log.e(TAG, "电源开启===主板轮询------ ");
                        sendPortData(sendString(0x02));
                    } else { //电源关闭
                        Log.e(TAG, "电源关闭===主板轮询------ ");
                        sendPortData(sendString(0x02));
                    }


                } else {   //微波炉轮询失败
                    Log.e(TAG, "微波炉轮询失败==开启微波炉电源------ ");
                    sendPortData(sendHeatString(0x8F, 0x10));
                }

            } else if (comBean.getbRec()[5] == 2) {
                if (comBean.getbRec().length > 52) {
                    if (comBean.getbRec()[52] == 1 && msign == 0) { //电源接通
                        msign = 1;
                        Log.e(TAG, "电源接通===主板轮询------ ");
                        sendPortData(sendString(0x02));


                    } else if (comBean.getbRec()[52] == 01) { //是否开始工作
                        if (comBean.getbRec()[56] == 01) { //开始加热
                            Log.e(TAG, "开始加热==加热中主板轮询------ ");
                            sendPortData(sendString(0x02));
                        } else { //未开始加热
                            Log.e(TAG, "未开始加热------ ");
                        }
                    } else if (comBean.getbRec()[52] == 0 && msign == 1) { //加热完成后电源从接通到端口
                        Log.e(TAG, "加热完成后电源从接通到端口------ ");
//                        intent();
                    } else {//电源未接通

                        msign = 0;
                        sendPortData(sendString(0x02));
                    }

                } else {
                    Log.e(TAG, "主板轮询出错==重新轮询------ ");
                    sendPortData(sendString(0x02));
                }


            }

        } else { //返回长度少于6的时候
            Log.e(TAG, "返回长度少于6的时候主板轮询----");
            sendPortData(sendHeatString(0x8F, 0x10));
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
//        sendPortData("4546CB0300900000f796");
        sendPortData(sendString(0x90));  //温度查询

//        sendPortData(sendHeatString(0x8F,0x10));
        myThread.setIsSleep(false);
    }

    @Override
    protected void onStop() {
        super.onStop();
        myThread.setIsSleep(true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        myThread.setIsSleep(true);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myThread.setIsStop(true);
        myThread.interrupt();

    }

    private class MyThread extends Thread {
        boolean isSleep = true;
        boolean isStop = false;

        @Override
        public void run() {
            //			int i = 0;
            while (!isInterrupted()) {
                synchronized (this) {
                    if (isSleep) {
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else {
                        Message msg = new Message();
                        msg.what = 1;
                        adHandle.sendMessage(msg);
                        waitTime++;
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            Thread.currentThread().interrupt();
                        }

                    }
                }
            }
        }

        public void setIsSleep(boolean isSleep) {
            this.isSleep = isSleep;
        }

        public void setIsStop(boolean isStop) {
            this.isStop = isStop;

        }

    }
}
